/*  tBookShelf: SharedPtr
    (C) 2007  TvN (Volodymyr Tarasenko), e-mail: tvntsr@yahoo.com

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#ifndef SHARED_PTR_UTILS_HPP
#define SHARED_PTR_UTILS_HPP

/// This solution is not thread safe, if you need thread safety 
/// take a look at boost::shared_ptr instead

class SharedCounter
{
public:
    SharedCounter(int i = 0)
    {
        counter = new int(i);
    }

    ~SharedCounter()
    {
        if (--(*counter) <= 0)
            delete counter;
    }

    SharedCounter(const SharedCounter& i)
        : counter(i.counter)
    {
        ++(*counter);
    }

    SharedCounter& operator=(const SharedCounter& i)
    {
        this->~SharedCounter();
        new(this) SharedCounter(i);

        return *this;
    }

    int operator()()
    {
        return *counter;
    }

private:
    int *counter;
};

template<typename T>
class SharedPtr
{
    typedef T value_type;
public:
    explicit 
    SharedPtr(T* i)
        : ptr(i), count(1)
    {}
    SharedPtr()
        : ptr(0), count(0)
    {
        ptr = new value_type;
    }

    SharedPtr(const SharedPtr& i)
        : ptr(i.ptr), count(i.count)
    {}

    ~SharedPtr()
    {
        if (count() <= 1)
            delete ptr;
    }

    SharedPtr& operator=(const SharedPtr& i)
    {
        if (count() <= 1)
            delete ptr;

        ptr   = i.ptr;
        count = i.count;

        return *this;
    }
    
    value_type* operator->()
    {
        return ptr;
    }

    value_type& operator*()
    {
        return *ptr;
    }

private:
    value_type*   ptr;
    SharedCounter count;
};

#endif //SHARED_PTR_UTILS_HPP
